<template>
  <div class="merchant-profile">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">个人资料</h1>
      <p class="text-gray-600 mt-1">管理您的个人信息和商家设置</p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 左侧个人信息卡片 -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div class="text-center">
            <!-- 头像 -->
            <div class="relative inline-block mb-4">
              <el-avatar :size="100" :src="getImageUrl(userStore.userInfo?.avatar)" class="border-4 border-white shadow-lg">
                <i class="fas fa-user text-4xl text-gray-400"></i>
              </el-avatar>
              <button 
                @click="showAvatarDialog = true"
                class="absolute bottom-0 right-0 bg-green-500 text-white rounded-full w-8 h-8 flex items-center justify-center hover:bg-green-600 transition-colors"
              >
                <i class="fas fa-camera text-sm"></i>
              </button>
            </div>
            
            <!-- 基本信息 -->
            <h3 class="text-xl font-semibold text-gray-800 mb-1">{{ userStore.userInfo?.username }}</h3>
            <p class="text-gray-500 mb-2">{{ userStore.userInfo?.email }}</p>
            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
              <i class="fas fa-store mr-1"></i>
              商家
            </span>
          </div>

          <!-- 统计信息 -->
          <div class="mt-6 pt-6 border-t border-gray-200">
            <div class="grid grid-cols-2 gap-4 text-center">
              <div>
                <div class="text-2xl font-bold text-green-500">{{ merchantStats.loginCount || 0 }}</div>
                <div class="text-sm text-gray-500">登录次数</div>
              </div>
              <div>
                <div class="text-2xl font-bold text-green-500">{{ merchantStats.operationCount || 0 }}</div>
                <div class="text-sm text-gray-500">操作次数</div>
              </div>
            </div>

            <!-- 最后登录信息 -->
            <div class="mt-4 pt-4 border-t border-gray-100 space-y-2">
              <div class="flex items-center justify-between text-sm">
                <span class="flex items-center text-gray-600">
                  <i class="fas fa-clock mr-2"></i>
                  最后登录:
                </span>
                <span class="text-gray-800">{{ formatLastLoginTime(merchantStats.lastLoginTime) }}</span>
              </div>
              <div class="flex items-center justify-between text-sm">
                <span class="flex items-center text-gray-600">
                  <i class="fas fa-map-marker-alt mr-2"></i>
                  登录IP:
                </span>
                <span class="text-gray-800">{{ merchantStats.lastLoginIp || '未知' }}</span>
              </div>
            </div>
          </div>


          
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="lg:col-span-2">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
          <!-- 标签页 -->
          <el-tabs v-model="activeTab" class="profile-tabs">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <div class="p-6">
                <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="100px">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <el-form-item label="用户名" prop="username">
                      <el-input v-model="profileForm.username" disabled />
                    </el-form-item>
                    
                    <el-form-item label="真实姓名" prop="realName">
                      <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" />
                    </el-form-item>
                    
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
                    </el-form-item>
                    
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
                    </el-form-item>
                    
                    <el-form-item label="性别" prop="gender">
                      <el-radio-group v-model="profileForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    
                    <el-form-item label="生日" prop="birthday">
                      <el-date-picker
                        v-model="profileForm.birthday"
                        type="date"
                        placeholder="选择生日"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </div>
                  
                  <div class="mt-6 flex justify-end">
                    <el-button @click="resetProfileForm">重置</el-button>
                    <el-button type="primary" @click="updateProfile" :loading="profileLoading">
                      保存修改
                    </el-button>
                  </div>
                </el-form>
              </div>
            </el-tab-pane>

            <!-- 商家信息 -->
            <el-tab-pane label="商家信息" name="merchant">
              <div class="p-6">
                <el-form :model="merchantForm" :rules="merchantRules" ref="merchantFormRef" label-width="100px">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <el-form-item label="店铺名称" prop="shopName">
                      <el-input v-model="merchantForm.shopName" placeholder="请输入店铺名称" />
                    </el-form-item>
                    
                    <el-form-item label="联系电话" prop="contactPhone">
                      <el-input v-model="merchantForm.contactPhone" placeholder="请输入联系电话" />
                    </el-form-item>
                    
                    <el-form-item label="营业执照号" prop="businessLicense">
                      <el-input v-model="merchantForm.businessLicense" placeholder="请输入营业执照号" />
                    </el-form-item>
                    
                    <el-form-item label="法人代表" prop="legalPerson">
                      <el-input v-model="merchantForm.legalPerson" placeholder="请输入法人代表" />
                    </el-form-item>
                  </div>
                  
                  <el-form-item label="店铺地址" prop="address">
                    <el-input 
                      v-model="merchantForm.address" 
                      type="textarea" 
                      :rows="3"
                      placeholder="请输入详细地址"
                    />
                  </el-form-item>
                  
                  <el-form-item label="店铺描述" prop="description">
                    <el-input 
                      v-model="merchantForm.description" 
                      type="textarea" 
                      :rows="4"
                      placeholder="请输入店铺描述"
                    />
                  </el-form-item>
                  
                  <div class="mt-6 flex justify-end">
                    <el-button @click="resetMerchantForm">重置</el-button>
                    <el-button type="primary" @click="updateMerchantInfo" :loading="merchantLoading">
                      保存修改
                    </el-button>
                  </div>
                </el-form>
              </div>
            </el-tab-pane>

            <!-- 安全设置 -->
            <el-tab-pane label="安全设置" name="security">
              <div class="p-6">
                <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                  <el-form-item label="当前密码" prop="currentPassword">
                    <el-input 
                      v-model="passwordForm.currentPassword" 
                      type="password" 
                      placeholder="请输入当前密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                      v-model="passwordForm.newPassword" 
                      type="password" 
                      placeholder="请输入新密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input 
                      v-model="passwordForm.confirmPassword" 
                      type="password" 
                      placeholder="请再次输入新密码"
                      show-password
                    />
                  </el-form-item>
                  
                  <div class="mt-6 flex justify-end">
                    <el-button @click="resetPasswordForm">重置</el-button>
                    <el-button type="primary" @click="updatePassword" :loading="passwordLoading">
                      修改密码
                    </el-button>
                  </div>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
      <div class="text-center">
        <div class="mb-4">
          <el-avatar :size="120" :src="previewAvatar || getImageUrl(userStore.userInfo?.avatar)">
            <i class="fas fa-user text-4xl text-gray-400"></i>
          </el-avatar>
        </div>
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-change="handleAvatarChange"
          :auto-upload="false"
          accept="image/*"
          ref="avatarUpload"
        >
          <el-button type="primary">
            <i class="fas fa-upload mr-2"></i>选择图片
          </el-button>
        </el-upload>
        <div class="text-sm text-gray-500 mt-2">
          支持 JPG、PNG 格式，文件大小不超过 20MB
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAvatarUpload">取消</el-button>
          <el-button type="primary" @click="handleUploadAvatar" :loading="uploadingAvatar" :disabled="!selectedAvatarFile">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { merchantAPI } from '@/api/merchant.js'

const userStore = useUserStore()

// 响应式数据
const activeTab = ref('basic')
const showAvatarDialog = ref(false)
const profileLoading = ref(false)
const merchantLoading = ref(false)
const passwordLoading = ref(false)
const uploadingAvatar = ref(false)
const previewAvatar = ref('')
const selectedAvatarFile = ref(null)

// 表单引用
const profileFormRef = ref()
const merchantFormRef = ref()
const passwordFormRef = ref()

// 商家统计数据
const merchantStats = ref({
  loginCount: 0,
  operationCount: 0,
  lastLoginTime: '未知',
  lastLoginIp: '未知'
})

// 个人信息表单
const profileForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  gender: 1,
  birthday: null
})

// 商家信息表单
const merchantForm = reactive({
  shopName: '',
  contactPhone: '',
  businessLicense: '',
  legalPerson: '',
  address: '',
  description: ''
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const merchantRules = {
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}



// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  if (url.startsWith('/uploads/')) return `http://localhost:8081/api${url}`
  if (url.startsWith('/assets/')) return `http://localhost:8081/api${url}`
  return `/api${url}`
}



// 重置表单数据
const resetProfileForm = () => {
  Object.assign(profileForm, {
    username: '',
    realName: '',
    email: '',
    phone: '',
    gender: 1,
    birthday: null
  })
}

// 加载商家个人资料
const loadMerchantProfile = async () => {
  try {
    const response = await merchantAPI.getMerchantProfile()
    if (response.code === 200) {
      const profile = response.data
      // 更新表单数据
      Object.assign(profileForm, {
        username: profile.username || '',
        realName: profile.realName || '',
        email: profile.email || '',
        phone: profile.phone || '',
        gender: profile.gender || 1,
        birthday: profile.birthDate ? new Date(profile.birthDate) : null
      })

      // 更新用户store
      userStore.updateUserInfo({
        ...userStore.userInfo,
        username: profile.username,
        email: profile.email,
        phone: profile.phone,
        realName: profile.realName,
        avatar: profile.avatar,
        gender: profile.gender,
        birthDate: profile.birthDate
      })
    }
  } catch (error) {
    console.error('加载商家资料失败：', error)
    ElMessage.error('加载个人资料失败')
  }
}

// 加载商家统计数据
const loadMerchantStats = async () => {
  try {
    const response = await merchantAPI.getMerchantStats()
    if (response.code === 200) {
      merchantStats.value = {
        loginCount: response.data.loginCount || 0,
        operationCount: response.data.operationCount || 0,
        lastLoginTime: response.data.lastLoginTime || '未知',
        lastLoginIp: response.data.lastLoginIp || '未知'
      }
    }
  } catch (error) {
    console.error('加载商家统计数据失败：', error)
    // 如果加载失败，保持默认值
    merchantStats.value = {
      loginCount: 0,
      operationCount: 0,
      lastLoginTime: '未知',
      lastLoginIp: '未知'
    }
  }
}

// 格式化最后登录时间
const formatLastLoginTime = (dateTime) => {
  if (!dateTime || dateTime === '未知') {
    return '暂无'
  }

  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return '暂无'
    }

    const now = new Date()
    const diff = now - date
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const minutes = Math.floor(diff / (1000 * 60))

    if (days > 0) {
      return `${days}天前`
    } else if (hours > 0) {
      return `${hours}小时前`
    } else if (minutes > 0) {
      return `${minutes}分钟前`
    } else {
      return '刚刚'
    }
  } catch (error) {
    return '暂无'
  }
}



// 更新个人信息
const updateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    profileLoading.value = true
    
    // 这里调用API更新个人信息
    // await merchantAPI.updateProfile(profileForm)
    
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  } finally {
    profileLoading.value = false
  }
}

// 更新商家信息
const updateMerchantInfo = async () => {
  try {
    await merchantFormRef.value.validate()
    merchantLoading.value = true
    
    // 这里调用API更新商家信息
    // await merchantAPI.updateMerchantInfo(merchantForm)
    
    ElMessage.success('商家信息更新成功')
  } catch (error) {
    console.error('更新商家信息失败:', error)
    ElMessage.error('更新商家信息失败')
  } finally {
    merchantLoading.value = false
  }
}

// 修改密码
const updatePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    // 调用API修改密码
    const response = await merchantAPI.changeMerchantPassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}



const resetMerchantForm = () => {
  Object.assign(merchantForm, {
    shopName: '',
    contactPhone: '',
    businessLicense: '',
    legalPerson: '',
    address: '',
    description: ''
  })
}

const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

// 头像上传相关
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt20M = file.size / 1024 / 1024 < 20

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt20M) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

// 处理文件选择
const handleAvatarChange = (uploadFile) => {
  if (!beforeAvatarUpload(uploadFile.raw)) {
    return
  }

  selectedAvatarFile.value = uploadFile.raw

  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(uploadFile.raw)
}

// 执行头像上传
const handleUploadAvatar = async () => {
  if (!selectedAvatarFile.value) {
    ElMessage.error('请先选择图片')
    return
  }

  try {
    uploadingAvatar.value = true

    const formData = new FormData()
    formData.append('file', selectedAvatarFile.value)

    const response = await merchantAPI.uploadAvatar(formData)

    if (response.code === 200) {
      ElMessage.success('头像上传成功')
      showAvatarDialog.value = false

      // 重新加载用户资料以获取最新信息
      await loadMerchantProfile()

      // 重置状态
      previewAvatar.value = ''
      selectedAvatarFile.value = null
    } else {
      ElMessage.error(response.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  } finally {
    uploadingAvatar.value = false
  }
}

// 取消头像上传
const cancelAvatarUpload = () => {
  showAvatarDialog.value = false
  previewAvatar.value = ''
  selectedAvatarFile.value = null
}

// 监听用户信息变化，当用户切换时重新加载数据
watch(() => userStore.userInfo?.id, async (newUserId, oldUserId) => {
  if (newUserId && newUserId !== oldUserId) {
    // 用户切换了，重新加载数据
    resetProfileForm()
    await loadMerchantProfile()
    await loadMerchantStats()
  }
}, { immediate: false })

onMounted(async () => {
  // 先重置表单数据，避免显示之前用户的信息
  resetProfileForm()
  // 然后加载当前用户的最新资料
  await loadMerchantProfile()
  // 加载商家统计数据
  await loadMerchantStats()
})
</script>

<style scoped>
.merchant-profile {
  min-height: 100vh;
}

.profile-tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 24px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e5e7eb;
}

.profile-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0;
}

.profile-tabs :deep(.el-tabs__content) {
  padding: 0;
}

.profile-tabs :deep(.el-tab-pane) {
  padding: 0;
}
</style>
